import { ref } from "vue";
import { getLanguageFromFileName } from "../utils/file-utils";

export function useFileSystem({ updateEditorContent }) {
  const fileTree = ref([]);
  const openedFiles = ref([]);
  const activeFile = ref(null);

  const fetchFileTree = async () => {
    try {
      const response = await fetch("http://localhost:8080/api/files/tree");
      if (!response.ok) throw new Error("获取文件树失败");
      fileTree.value = await response.json();
    } catch (error) {
      console.error("获取文件树错误:", error);
    }
  };

  const handleFileClick = async (node) => {
    if (!node.directory) {
      try {
        if (!openedFiles.value.find((f) => f.path === node.path)) {
          const response = await fetch(
            `http://localhost:8080/api/files/content?path=${encodeURIComponent(
              node.path
            )}`
          );
          if (!response.ok) throw new Error("Failed to load file content");
          const content = await response.text();

          openedFiles.value.push({
            path: node.path,
            name: node.name,
            content: content,
          });
        }
        activeFile.value = node.path;

        const file = openedFiles.value.find((f) => f.path === node.path);
        updateEditorContent(file.content, getLanguageFromFileName(file.name));
      } catch (error) {
        console.error("Error loading file:", error);
      }
    }
  };

  const handleCloseTab = (path) => {
    const index = openedFiles.value.findIndex((f) => f.path === path);
    if (index !== -1) {
      openedFiles.value.splice(index, 1);
      if (activeFile.value === path) {
        activeFile.value =
          openedFiles.value.length > 0 ? openedFiles.value[0].path : null;
        if (activeFile.value) {
          const newActiveFile = openedFiles.value.find(
            (f) => f.path === activeFile.value
          );
          updateEditorContent(
            newActiveFile.content,
            getLanguageFromFileName(newActiveFile.name)
          );
        }
      }
    }
  };

  const handleSelectTab = (path) => {
    activeFile.value = path;
    const file = openedFiles.value.find((f) => f.path === path);
    if (file) {
      updateEditorContent(file.content, getLanguageFromFileName(file.name));
    }
  };

  return {
    fileTree,
    openedFiles,
    activeFile,
    fetchFileTree,
    handleFileClick,
    handleCloseTab,
    handleSelectTab,
  };
}
